<?php

require('./common.php');

$user->session_start(array('req_login' => true));

$mode     = (string) @$_POST['mode'];
$blog_id  = (int)    @$_POST['blog_id'];
$vote_id  = (int)    @$_POST['vote_id'];

$return_blog_url = BLOG_URL . $blog_id;
$return_blog_url .= !empty($_POST['start']) ? "&amp;start=". intval($_POST['start']) : '';

set_die_append_msg($blog_id);

$poll = new ts_poll();

// проверка валидности $blog_id
if (!$blog_id)
{
	ts_die('Invalid blog_id');
}
if (!$t_data = DB()->fetch_row("SELECT * FROM ". TS_BLOGS ." WHERE blog_id = $blog_id LIMIT 1"))
{
	ts_die('Blog not found');
}

// проверка на возможность вносить изменения
if ($mode == 'poll_delete')
{
	if ($t_data['blog_time'] < TIMENOW - $ts_cfg['poll_max_days'] * 86400)
	{
		ts_die(sprintf($lang['NEW_POLL_DAYS'], $ts_cfg['poll_max_days']));
	}
	if (!IS_ADMIN && ($t_data['blog_vote'] != POLL_FINISHED))
	{
		ts_die($lang['CANNOT_DELETE_POLL']);
	}
}

switch ($mode)
{
	// голосование
	case 'poll_vote':
		if (!$t_data['blog_vote'])
		{
			ts_die($lang['POST_HAS_NO_POLL']);
		}
		if (!poll_is_active($t_data))
		{
			ts_die($lang['NEW_POLL_ENDED']);
		}
		if (!$vote_id)
		{
			ts_die($lang['NO_VOTE_OPTION']);
		}
		if (DB()->fetch_row("SELECT 1 FROM ". TS_POLL_USERS ." WHERE blog_id = $blog_id AND user_id = {$userdata['user_id']} LIMIT 1"))
		{
			ts_die($lang['ALREADY_VOTED']);
		}
		DB()->query("
			UPDATE ". TS_POLL_VOTES ." SET
				vote_result = vote_result + 1
			WHERE blog_id = $blog_id
				AND vote_id = $vote_id
			LIMIT 1
		");
		if (DB()->affected_rows() != 1)
		{
			ts_die($lang['NO_VOTE_OPTION']);
		}
		DB()->query("INSERT IGNORE INTO ". TS_POLL_USERS ." (blog_id, user_id, vote_ip, vote_dt) VALUES ($blog_id, {$userdata['user_id']}, '". USER_IP ."', ". TIMENOW .")");
		
		CACHE('ts_poll_data')->rm("poll_$blog_id");
		
		ts_die($lang['VOTE_CAST']);
		
		break;
		
	// возобновить возможность голосовать
	case 'poll_start':
		if (!$t_data['blog_vote'])
		{
			ts_die($lang['POST_HAS_NO_POLL']);
		}
		DB()->query("UPDATE ". TS_BLOGS ." SET blog_vote = 1 WHERE blog_id = $blog_id LIMIT 1");
		ts_die($lang['NEW_POLL_START']);
		break;
		
		
	// завершить опрос
	case 'poll_finish':
		if (!$t_data['blog_vote'])
		{
			ts_die($lang['POST_HAS_NO_POLL']);
		}
		DB()->query("UPDATE ". TS_BLOGS ." SET blog_vote = ". POLL_FINISHED ." WHERE blog_id = $blog_id LIMIT 1");
		ts_die($lang['NEW_POLL_END']);
		break;
		
	// удаление
	case 'poll_delete':
		if (!$t_data['blog_vote'])
		{
			ts_die($lang['POST_HAS_NO_POLL']);
		}
		$poll->delete_poll($blog_id);
		ts_die($lang['NEW_POLL_DELETE']);
		break;
		
	// добавление
	case 'poll_add':
		if ($t_data['blog_vote'])
		{
			ts_die($lang['NEW_POLL_ALREADY']);
		}
		$poll->build_poll_data($_POST);
		if ($poll->err_msg)
		{
			ts_die($poll->err_msg);
		}
		$poll->insert_votes_into_db($blog_id);
		ts_die($lang['NEW_POLL_ADDED']);
		break;
	
	// редакторование
	case 'poll_edit':
		if (!$t_data['blog_vote'])
		{
			ts_die($lang['POST_HAS_NO_POLL']);
		}
		$poll->build_poll_data($_POST);
		if ($poll->err_msg)
		{
			ts_die($poll->err_msg);
		}
		$poll->insert_votes_into_db($blog_id);
		CACHE('ts_poll_data')->rm("poll_$blog_id");
		ts_die($lang['NEW_POLL_RESULTS']);
		break;
		
	default:
		bb_die('Invalid mode: '. htmlCHR($mode));
}

// Functions
class ts_poll
{
	var $err_msg    = '';
	var $poll_votes = array();
	var $max_votes  = 0;
	
	function ts_poll ()
	{
		global $ts_cfg;
		$this->max_votes = $ts_cfg['max_poll_options'];
	}
	
	function build_poll_data ($posted_data)
	{
		$poll_caption = (string) @$posted_data['poll_caption'];
		$poll_votes   = (string) @$posted_data['poll_votes'];
		$this->poll_votes = array();
		
		if (!$poll_caption = str_compact($poll_caption))
		{
			global $lang;
			return $this->err_msg = $lang['EMPTY_POLL_TITLE'];
		}
		$this->poll_votes[] = $poll_caption; // заголовок имеет vote_id = 0
		
		foreach (explode("\n", $poll_votes) as $vote)
		{
			if (!$vote = str_compact($vote))
			{
				continue;
			}
			$this->poll_votes[] = $vote;
		}
		
		// проверять на "< 3" -- 2 варианта ответа + заголовок
		if (count($this->poll_votes) < 3 || count($this->poll_votes) > $this->max_votes + 1)
		{
			global $lang;
			return $this->err_msg = sprintf($lang['NEW_POLL_VOTES'], $this->max_votes);
		}
	}
	
	function insert_votes_into_db ($blog_id)
	{
		$this->delete_votes_data($blog_id);
		$sql_ary = array();
		
		foreach ($this->poll_votes as $vote_id => $vote_text)
		{
			$sql_ary[] = array(
				'blog_id'     => (int) $blog_id,
				'vote_id'     => (int) $vote_id,
				'vote_text'   => (string) $vote_text,
				'vote_result' => (int) 0,
			);
		}
		$sql_args = DB()->build_array('MULTI_INSERT', $sql_ary);
		
		DB()->query("REPLACE INTO ". TS_POLL_VOTES . $sql_args);
		
		DB()->query("UPDATE ". TS_BLOGS ." SET blog_vote = 1 WHERE blog_id = $blog_id LIMIT 1");
	}
	
	function delete_poll ($blog_id)
	{
		DB()->query("UPDATE ". TS_BLOGS ." SET blog_vote = 0 WHERE blog_id = $blog_id LIMIT 1");
		$this->delete_votes_data($blog_id);
	}
	
	function delete_votes_data ($blog_id)
	{
		DB()->query("DELETE FROM ". TS_POLL_VOTES ." WHERE blog_id = $blog_id");
		DB()->query("DELETE FROM ". TS_POLL_USERS ." WHERE blog_id = $blog_id");
		CACHE('ts_poll_data')->rm("poll_$blog_id");
	}
}